package priv.dajie.tzzq.spider.csgo.c5;

import org.apache.http.client.methods.HttpGet;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import priv.dajie.tzzq.Base;
import priv.dajie.tzzq.spider.csgo.SpiderInfoElement;
import priv.dajie.tzzq.spider.csgo.SpiderInfos;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @ClassName C5CsgoInfo
 * @Description
 * @Author dajie
 * @Date 2019/11/9 11:16 下午
 * @Version V1.0
 **/
public class C5CsgoInfo {

    private static Base httpclient = Base.getClientInstance();
    private static Pattern paramePattern = Pattern.compile("\\?(.*)&page");

    public static SpiderInfos getSpiderInfos(){
        String html = httpclient.open(new HttpGet("https://www.c5game.com/csgo/default/result.html"));
        Document document = Jsoup.parse(html);
        Elements items = document.select("a.product_type");
//        Map<SpiderInfoElement, String> map = new HashMap<>();
        List<SpiderInfoElement> infoElements = new ArrayList<>();
        for (Element item : items) {
            if (item.classNames().size()>1){
                continue;
            }
            String url = item.attr("href");
            String parameStr = null;
            Matcher matcher = paramePattern.matcher(url);
            if (matcher.find()){
                parameStr = matcher.group(1);
            }else{
                throw new RuntimeException("解析链接时出错！");
            }
            String name = item.text();
            String[] parame = parameStr.split("=", 2);
            SpiderInfoElement infoElement = new SpiderInfoElement();
            infoElement.setKey(parame[0]);
            infoElement.setValue(parame[1]);
            infoElement.setTypeName(name);
            infoElements.add(infoElement);

        }
        return new SpiderInfos(infoElements);
    }

    public static void main(String[] args) {
        SpiderInfos spiderInfos = getSpiderInfos();

        System.out.println(spiderInfos);
    }
}
